//
//  RHDeviceInfoBaseVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/12/5.
//

#import "RHDeviceInfoBaseVC.h"
#import "RHNormalCell.h"
#import "CBLECenterMnger.h"
#import "RHBleCmdData.h"

@interface RHDeviceInfoBaseVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) UIView *headerView;


@property (nonatomic ,strong) QMUILabel *plantNameLab;

@property (nonatomic ,strong) QMUIButton *addressBtn;

@property (nonatomic ,strong) NSMutableArray *batteryArr;

@property (nonatomic ,strong) NSMutableArray *softWareArr;

@property (nonatomic ,strong) UIImageView *plantImg;
@end

@implementation RHDeviceInfoBaseVC

-(NSMutableArray *)softWareArr
{
    if(!_softWareArr){
        _softWareArr = [NSMutableArray array];
    }
    return _softWareArr;
}
-(NSMutableArray *)batteryArr
{
    if(!_batteryArr){
        _batteryArr = [NSMutableArray array];
    }
    return _batteryArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.navigationItem.title = self.infoModel.sectionTitle.rh_localized;
    [self getData];
    [self setupUI];
}

-(void)getData
{
    
    [self getDeviceInfo];
    
}

-(void)setupUI{
    
    
    
    kWeakSelf;
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView registerClass:[RHNormalCell class] forCellReuseIdentifier:@"RHNormalCell"];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setSeparatorColor:UIColor.clearColor];
    //iOS 12 在tableView为StyleGrouped情况下会 往下偏移35,加上这个后解决
    _tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0.001)];
    _tableView.tableFooterView = [UIView new];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    //站点信息
    if([self.infoModel.infoType isEqualToString:@"station"]){
        _tableView.tableHeaderView = self.headerView;
    }
    [self.view addSubview:_tableView];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    
 
    [_tableView addHeaderRefresh:^{
        [weakSelf getDeviceInfo];
    }];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
}



//设备详情
-(void)getDeviceInfo
{
    NSDictionary *para = @{@"deviceId":ValidNullData(self.deviceModel.deviceId),
                           @"messageType":@(self.infoModel.requestId)
                          };
    [QMUITips showLoadingInView:self.view];
    [BaseModel startGetWithCompletionAPIKey:H_getDeviceDetails_v1 argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200 ){
            [self.infoModel readDeviceInfo:request.responseJSONObject[@"data"]];
            [self.tableView reloadData];
            //站点信息
            if([self.infoModel.infoType isEqualToString:@"station"]) {
                if ([request.responseJSONObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *dic = request.responseJSONObject[@"data"];
                    self.plantNameLab.text = ValidNullDataToString(dic[@"plantName"], @"--");
                    [self.addressBtn setTitle:ValidNullDataToString(dic[@"address"], @"--") forState:UIControlStateNormal];
                    if([ValidNullData(dic[@"imageUrl"]) length]>0){
                        [self.plantImg sd_setImageWithURL:[NSURL URLWithString:dic[@"imageUrl"]] placeholderImage:[UIImage imageNamed:@"plant_default_pic_01"]];
                    }
                }
                
            }
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        [self.tableView endHeaderRefresh];
    }];
}



#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return self.infoModel.rows.count;
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return nil;//取消
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 65)];
    headerView.backgroundColor = CFTabViewBgColor;
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 15, kUI_WINDOW_W-30, 50)];
    [headerView addSubview:bgView];
    bgView.layer.cornerRadius = 8;
    bgView.layer.masksToBounds = YES;
    bgView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
    bgView.backgroundColor = [UIColor whiteColor];
    
    
    UIImageView *icon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:self.infoModel.icon]];
    icon.contentMode = UIViewContentModeScaleAspectFill;
    [bgView addSubview:icon];
    
    UILabel *titleLab = [[QMUILabel alloc]init];
    titleLab.font = kBOLDSYSTEMFONT(15);
    titleLab.textColor = kCOLOR_HEX(@"3F4443");
    titleLab.textAlignment = NSTextAlignmentLeft;
    titleLab.text = self.infoModel.sectionTitle.rh_localized;
    [bgView addSubview:titleLab];
    
    UIView *line = kView;
    line.backgroundColor = kCOLOR_HEX(@"EBEDF0");
    [bgView addSubview:line];
    
    [icon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(@(CGSizeMake(20, 20)));
        make.left.mas_offset(15);
        make.centerY.mas_offset(0);
    }];
    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(icon.mas_right).offset(15);
        make.centerY.equalTo(icon);
     }];
    
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.offset(1);
        make.bottom.mas_offset(-5);
    }];
   return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
//    UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 20)];
//    footer.backgroundColor = CFTabViewBgColor;
//    UIView *subView = [[UIView alloc]initWithFrame:CGRectMake(15, 0, footer.width-30, 10)];
//    subView.backgroundColor = [UIColor whiteColor];
//    [subView setBottomBorder];
//    [footer addSubview:subView];
//    return footer;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    RHNormalCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHNormalCell"];
    
    PEDevInfoRowModel *rowModel = self.infoModel.rows[indexPath.row];
    cell.snLab.text = nil;
    cell.titleLab.text = rowModel.title.rh_localized;
    cell.contentLab.text = rowModel.content;
    if (rowModel.sn.length>0) {
        cell.snLab.text = [NSString stringWithFormat:@"SN:%@",rowModel.sn];
    }
    
    //电站的单位放在title里
//    if([self.infoModel.infoType isEqualToString:@"station"]){
        cell.titleLab.text = [NSString stringWithFormat:@"%@%@:",rowModel.title.rh_localized,ValidNullData(rowModel.unit).rh_localized];
//    }else{
//        //除电站信息外,其他的单位放在数值里
//        cell.contentLab.text = [NSString stringWithFormat:@"%@%@",rowModel.content,ValidNullData(rowModel.unit)];
//    }
//    if([self.infoModel.infoType isEqualToString:@"battery"]){
//        cell.titleLab.text = [NSString stringWithFormat:@"%@:",rowModel.title.rh_localized];
//    }
    
    //电站安装时间
    if([rowModel.key isEqualToString:@"createTime"]){
        cell.contentLab.text = [NSDate dateStringWithTimeInterval:[rowModel.content integerValue]/1000 formatter:@"yyyy/MM/dd HH:mm:ss"];
        if ([rowModel.content integerValue]==0) {
            cell.contentLab.text = @"--";
        }
    }
    
    CGFloat width = [cell.contentLab.text getStringWidthFont:cell.contentLab.font limitHeight:20] + 5;
    [cell.contentLab mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.offset(width);
    }];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.row == 0) {
        [cell.bgView setTopBorder];
    }else if(indexPath.row == self.infoModel.rows.count - 1){
        [cell.bgView setBottomBorder];
    }else{
        [cell.bgView setMiddleBorder];
    }
    cell.line.hidden = (indexPath.row == self.infoModel.rows.count - 1);
    return cell;

}

-(UIView *)headerView
{
    if(!_headerView){
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, kUI_WINDOW_W*214/375.0)];
        
        UIView *bgView = [[UIView alloc] init];
        [bgView setBackgroundColor:CFTabViewBgColor];
        [_headerView addSubview:bgView];
        
        [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsMake(0,0, 0, 0));
        }];
        
        UIImageView *plantImageV = [[UIImageView alloc] init];
        plantImageV.clipsToBounds = YES;
        plantImageV.contentMode = UIViewContentModeScaleAspectFill;
        [plantImageV setImage:[UIImage imageNamed:@"plant_default_pic_01"]];
        self.plantImg = plantImageV;
        [bgView addSubview:plantImageV];
        
        [plantImageV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsZero);
        }];
       
        QMUIButton *adressBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
        [adressBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [adressBtn setImage:[UIImage imageNamed:@"plant_address_icon_01"] forState:UIControlStateNormal];
        [adressBtn setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
        [adressBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
        [adressBtn setImagePosition:QMUIButtonImagePositionLeft];
        [adressBtn setSpacingBetweenImageAndTitle:5];
        [bgView addSubview:adressBtn];
        self.addressBtn = adressBtn;
        
        [adressBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(10);
            make.bottom.mas_offset(-15);
            make.width.lessThanOrEqualTo(@(kUI_WINDOW_W-40));
        }];
        
        QMUILabel *plantName = [[QMUILabel alloc]init];
        plantName.text = @"--";
        plantName.textColor = UIColor.whiteColor;
        plantName.font = kSYSTEMFONT(34);
        [bgView addSubview:plantName];
        self.plantNameLab = plantName;
        [plantName mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.centerY.mas_offset(0);
        }];
        
    }
    return _headerView;
}
@end
